const express = require("express")
const router = express.Router()
const messageDB = require("../../db/message")
const { sensitiveVer } = require('../../utils/sensitiveVerification')

// 留言
router.post("/mes", async (req, res) => {
  try {
    let { name, email, phone, message } = req.body.data

    if (!name.trim()) {
      return res.send({
        code: 18,
        mes: "留言者姓名不能为空哦"
      })
    }
    if (!email.trim()) {
      return res.send({
        code: 19,
        mes: "留言者邮箱不能为空哦"
      })
    }
    if (!phone.trim()) {
      return res.send({
        code: 20,
        mes: "留言者联系方式不能为空哦"
      })
    }
    if (!message.trim()) {
      return res.send({
        code: 21,
        mes: "留言内容不能为空哦"
      })
    }

    await sensitiveVer(name)
    await sensitiveVer(message)
    await messageDB.create(req.body.data)
    res.send({
      code: 0,
      mes: "留言成功！"
    })
  } catch (error) {
    res.send({
      code: 5,
      mes: error || "服务器异常，请稍后再试"
    })
  }
})

// 获取留言
router.post("/getMes", async (req, res) => {
  try {
    let { read } = req.body
    if (read === undefined) {
      let doc = await messageDB.find()
      res.send({
        code: 0,
        mes: "文章留言列表",
        data: doc
      })
      return
    }
    let doc = await messageDB.find({ read }, {}, {
      sort: {
        date: -1
      }
    })
    console.log(doc)
    return res.send({
      code: 0,
      mes: "文章留言列表",
      data: doc
    })
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试"
    })
  }
})

// 删除留言
router.use("/delete", require("./delete"))

// 消息处理
router.use("/update", require("./update"))

module.exports = router